#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

LTNode* LTBuyNode(LTDataType x)
{
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL)
	{
		perror("malloc fail!");
	}
	node->data = x;
	node->next = node->prev = node;
	return node;
}

void LTInit(LTNode** pphead)
{
	*pphead = LTBuyNode(-1);
}
//LTNode* LTInit()
//{
//	LTNode* phead = LTBuyNode(-1);
//	return phead;
//}

void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newcode = LTBuyNode(x);

	newcode->prev = phead->prev;
	newcode->next = phead;

	phead->prev->next = newcode;
	phead->prev = newcode;
}

void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newcode = LTBuyNode(x);

	newcode->next = phead->next;
	newcode->prev = phead;

	phead->next->prev = newcode;
	phead->next = newcode;
}

void LTPrint(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}
void LTPopBack(LTNode* phead)
{
	assert(phead && phead->next != phead);

	LTNode* del = phead->prev;

	del->prev->next = phead;
	phead->prev = del->prev;
	
	free(del);
	del = NULL;
}

void LTPopFront(LTNode* phead)
{
	assert(phead && phead->next != phead);

	LTNode* del = phead->next;
	phead->next = del->next;
	del->prev = phead;

	free(del);
	del = NULL;
}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* newcode = LTBuyNode(x);

	newcode->next = pos->next;
	newcode->prev = pos;

	pos->next->prev = newcode;
	pos->next = newcode;
}

void LTErase(LTNode* pos)
{
	assert(pos);
	
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;

	free(pos);
	pos = NULL;
}

void LTDestroy(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;

	while (pcur != phead)
	{
		LTNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	free(phead);
	phead = NULL;
}